<template>
  <div class="template-detail w-full h-full flex">
    <div class="detail-box left-info flex-column">
      <div class="detail-title">
        <div>基本信息：</div>
        <a-button type="primary" @click="saveBasicInfo">保存</a-button>
      </div>
      <div class="m-b-sm m-t-sm">模板名称：</div>
      <a-input v-model="templateInfo.name" class="m-b-md"></a-input>
      <div class="m-b-sm">描述信息：</div>
      <a-input v-model="templateInfo.desc" class="m-b-md"></a-input>
      <div class="m-b-sm w-full flex justify-content-between align-center">
        <div>表单列表：</div>
        <a-button type="primary" @click="openAddFormDialog">新增</a-button>
      </div>
      <div style="flex:1;overflow-y: auto">
        <div
            class="item"
            :class="{'item-active': activeForm === item.id }"
            v-for="item in formList"
            :key="item.id"
            @mouseenter="mouseEnterForm = item.id"
            @mouseleave="mouseEnterForm = ''"
            @click="handleFormClick(item)">
          <div class="name" :title="item.formName">{{item.formName}}</div>
          <a-icon v-show="activeForm === item.id || mouseEnterForm === item.id" @click.stop="handleDeleteForm(item.id)" title="删除" type="close"  style="color: red;cursor: pointer"/>
        </div>
      </div>
      <div style="display: flex;justify-content: flex-end">
        <a-button type="primary" style="width: 64px;" @click="showTestDialog">测试</a-button>
      </div>
    </div>
    <div class="detail-box center-info flex-column">
      <div class="detail-title">
        <div>表单信息：</div>
        <a-button type="primary" @click="saveConfigFormInfo">保存</a-button>
      </div>
      <div style="flex:1;overflow-y: auto;position: relative">
        <div class="item-detail" v-show="configFormInfo.id">
          <div class="m-b-sm m-t-sm">表单ID：</div>
          <a-input v-model="configFormInfo.formId" class="m-b-md" disabled></a-input>
          <div class="m-b-sm m-t-sm">表单名称：</div>
          <a-input v-model="configFormInfo.formName" class="m-b-md"></a-input>
          <div class="m-b-sm">表单别名：</div>
          <a-input v-model="configFormInfo.formNick" class="m-b-md"></a-input>
          <div class="m-b-sm">环节名称：（用于校验项目数据时根据环节过滤是否展示）</div>
          <a-select
            mode="tags"
            style="width: 100%"
            class="m-b-md"
            :token-separators="[',']"
            :open="false"
            v-model="configFormInfo.activityName">
          </a-select>
          <div class="m-b-sm">图标：</div>
          <div class="icon-sel">
            <a-input disabled v-model="configFormInfo.icon" class="m-b-md"></a-input>
            <a-button type="primary" @click="showIconSelDialog">选择</a-button>
          </div>
          <div class="m-b-sm">为空是否跳过：</div>
          <a-select
            v-model="configFormInfo.jumpEmpty"
            style="width: 100%"
            class="m-b-md"
          >
            <a-select-option :value="'true'">
              是
            </a-select-option>
            <a-select-option :value="'false'">
              否
            </a-select-option>
          </a-select>
          <div class="m-b-sm">排列方向：</div>
          <a-select
            v-model="configFormInfo.direction"
            style="width: 100%"
            class="m-b-md"
          >
            <a-select-option :value="'row'">
              横向
            </a-select-option>
            <a-select-option :value="'col'">
              纵向
            </a-select-option>
          </a-select>
          <div class="m-b-sm">展示高度：</div>
          <a-input v-model="configFormInfo.showHeight" class="m-b-md"></a-input>
          <div class="m-b-sm">排序：</div>
          <a-input type="number" v-model="configFormInfo.sortNum" class="m-b-md"></a-input>
          <div class="m-b-sm">过滤脚本ID：</div>
          <a-input v-model="configFormInfo.script" class="m-b-md"></a-input>
        </div>
        <div v-show="fieldList.length" class="detail-title" style="position: sticky;top: 0;background-color: white;z-index: 99;padding: 10px 0">
          <div>字段列表：</div>
          <a-button type="primary" @click="initFieldList">初始化</a-button>
        </div>
        <div
          class="item"
          :class="{'item-active': activeField === item.id}"
          v-for="item in fieldList"
          :key="item.id"
          @mouseenter="mouseEnterField = item.id"
          @mouseleave="mouseEnterField = ''"
          @click="handleFieldClick(item)">
          <div class="name" :title="`${item.tableName}.${item.fieldName}（${item.fieldNick}）`">{{item.tableName}}.{{item.fieldName}}（{{item.fieldNick}}）</div>
          <a-icon v-show="activeField === item.id || mouseEnterField === item.id" @click.stop="handleDeleteFormItem(item.id)" title="删除" type="close"  style="color: red;cursor: pointer"/>
        </div>
      </div>
    </div>
    <div class="detail-box right-info flex-column">
      <div class="detail-title">
        <div>配置信息：</div>
        <a-button type="primary" @click="updateConfigFormItem">保存</a-button>
      </div>
      <div v-show="fieldInfo.id" style="flex:1;overflow-y: auto;padding-top: 10px;padding-bottom: 30px">
        <div class="m-b-sm">字段英文名：</div>
        <div class="m-b-md">
          <a-input disabled v-model="fieldInfo.fieldName"></a-input>
        </div>
        <div class="m-b-sm">字段别名：</div>
        <div class="m-b-md">
          <a-input v-model="fieldInfo.fieldNick"></a-input>
        </div>
        <div class="m-b-sm">所属表英文名：</div>
        <div class="m-b-md">
          <a-input disabled v-model="fieldInfo.tableName"></a-input>
        </div>
        <div class="m-b-sm">所属表别名：</div>
        <div class="m-b-md">
          <a-input disabled v-model="fieldInfo.tableNick"></a-input>
        </div>
        <div class="m-b-sm">排序：</div>
        <div class="m-b-md">
          <a-input type="number" v-model="fieldInfo.sortNum"></a-input>
        </div>
        <a-checkbox class="m-b-md" :checked="fieldInfo.required" @change="fieldInfo.required = !fieldInfo.required">
          是否必填（对于空字符串 仅空格 也将进行校验限制）
        </a-checkbox>
        <div class="m-b-sm">自定义必填提示：</div>
        <div class="m-b-md">
          <a-input v-model="fieldInfo.requiredDesc"></a-input>
        </div>
        <div class="m-b-sm">最大长度：</div>
        <div class="m-b-md">
          <a-input v-model="fieldInfo.limitLength"></a-input>
        </div>
        <div class="m-b-sm">内容限制（以字典的方式进行可输入内容的限制）：</div>
        <div class="m-b-md">
          <a-select
            allow-clear
            show-search
            placeholder="请选择数据字典"
            v-model="fieldInfo.checkDicName"
            style="width: 98%"
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option v-for="item in dicList" :key="item.id" :value="item.name">
              {{item.name}}
            </a-select-option>
          </a-select>
        </div>
        <a-checkbox class="m-b-md" :checked="fieldInfo.needDecode" @change="fieldInfo.needDecode = !fieldInfo.needDecode">
          是否加密
        </a-checkbox>
        <div class="m-b-sm">扩展字典（用于拓展的数据字典,可用于自定义js校验的输入）：</div>
        <div class="m-b-md">
          <a-select
            mode="multiple"
            allow-clear
            show-search
            placeholder="请选择数据字典"
            style="width: 98%"
            option-filter-prop="children"
            :filter-option="filterOption"
            v-model="extendDicArray"
            @change="handleExtendDicArrayChange"
          >
            <a-select-option v-for="item in dicList" :key="item.id" :value="item.name">
              {{item.name}}
            </a-select-option>
          </a-select>
        </div>
        <div class="detail-title">
          <div>自定义脚本校验：</div>
          <div>
            <a-button class="m-r-xs" type="primary" @click="addSciptltem('add')">新增</a-button>
            <a-button type="primary" @click="addSciptltem('save')">保存</a-button>
          </div>
        </div>
        <a-table
          bordered
          :loading="table.loading"
          :rowKey="(record, index)=>index"
          :columns="table.columns"
          :data-source="table.dataSource"
          :pagination="false"
          :scroll="{ x: false }"
        >
          <template slot="showInput" slot-scope="text,record,index,column">
            <div v-if="activeScript === record.id">
              <a-input v-if="column.dataIndex==='sortNo'" type="number" v-model="record[column.dataIndex]"></a-input>
              <a-input v-else v-model="record[column.dataIndex]"></a-input>
            </div>
            <div v-else>{{text}}</div>
          </template>
          <template slot="opt" slot-scope="text,record">
            <div>
              <span class="script-btn m-r-sm" @click="activeScript = record.id">编辑</span>
              <span class="script-btn" style="color: #ff4d4f" @click="deleteScript(record.id)">删除</span>
            </div>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
  import dataQualityInspectionService from '@/api/dataQualityInspectionService'
  import dicService from '@/api/dicService'
  import dataMappingService from '@/api/dataMappingService'
export default {
  name: 'TemplateDetail',
  data () {
    return {
      templateInfo: {},
      formList: [],
      activeForm: '',
      mouseEnterForm: '',
      fieldList: [],
      activeField: '',
      mouseEnterField: '',
      fieldInfo: {},
      dicList: [],
      extendDicArray: [],
      scriptList: [],
      table: {
        columns: [
          {
            title: '名称',
            dataIndex: 'scriptName',
            align: 'center',
            scopedSlots: { customRender: 'showInput' }
          },
          {
            title: '脚本ID',
            dataIndex: 'scriptId',
            align: 'center',
            scopedSlots: { customRender: 'showInput' }
          },
          {
            title: '排序',
            dataIndex: 'sortNo',
            align: 'center',
            width: '80px',
            scopedSlots: { customRender: 'showInput' }
          },
          {
            title: '操作',
            dataIndex: 'opt',
            align: 'center',
            width: '130px',
            scopedSlots: { customRender: 'opt' }
          }
        ],
        dataSource: [],
        loading: false
      },
      activeScript: '',
      configFormInfo: {}
    }
  },
  props: {
    template: {
      type: Object,
      default: () => {}
    }
  },
  created () {
    this.templateInfo = { ...this.template }
  },
  mounted () {
    this.getFormList()
    this.getDicList()
    this.getScriptList()
  },
  methods: {
    async getFormList () {
      const data = await dataQualityInspectionService.listConfigFormByConfigId({
        configId: this.templateInfo.id
      })
      this.formList = data || []
    },
    async handleFormClick (item) {
      this.activeForm = item.id
      this.activeField = ''
      this.fieldInfo = {}
      await this.getFieldList()
      await this.getConfigFormInfo()
    },
    async getConfigFormInfo () {
      const data = await dataQualityInspectionService.getConfigFormByConfigFormId({
        configFormId: this.activeForm,
        loadDetail: false
      })
      data.jumpEmpty = typeof data.jumpEmpty === 'boolean' ? String(data.jumpEmpty) : ''
      data.activityName = data.activityName ? data.activityName.split(',') : []
      this.configFormInfo = data
    },
    async getFieldList () {
      const data = await dataQualityInspectionService.listConfigFormItemByConfigFormId({
        configFormId: this.activeForm
      })
      this.fieldList = data || []
    },
    openAddFormDialog () {
      const _this = this
      this.$dialog({
        title: '新增表单',
        content: () => import('./dialog/addFormDialog'),
        width: 400,
        centered: true,
        maskClosable: false,
        on: {
          ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            if (dialogCtl.formIds.length) {
              _this.doAddForm(dialogCtl.formIds)
            }
            ctl.closeDialog()
          }
        }
      })
    },
    async doAddForm (formIds) {
      const params = {
        configId: this.templateInfo.id
      }
      const data = []
      formIds.forEach(id => {
        data.push({
          formId: id
        })
      })
      await dataQualityInspectionService.addConfigForm(params, data)
      await this.getFormList()
    },
    async handleFieldClick (item) {
      this.activeField = item.id
      this.fieldInfo = item
      this.extendDicArray = item.extendDicNames?.split(',') || []
      await this.listScriptItemByFormItemId(item.id)
    },
    async getDicList () {
      const data = await dicService.searchDictionary()
      this.dicList = data.rows
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    async getScriptList () {
      const data = await dataMappingService.getAllScriptList({}, {})
      this.scriptList = data.rows
    },
    async handleDeleteForm (id) {
      this.$confirm({
        title: '提示',
        content: '确认执行删除操作，删除后不可恢复！',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          if (this.activeForm === id) {
            this.activeForm = ''
            this.fieldList = []
            this.fieldInfo = {}
            this.configFormInfo = {}
          }
          await dataQualityInspectionService.deleteConfigFormById({
            ids: [id]
          })
          await this.getFormList()
          this.$message.success('删除成功')
        }
      })
    },
    async handleDeleteFormItem (id) {
      if (this.activeField === id) {
        this.activeField = ''
        this.fieldInfo = {}
      }
      await dataQualityInspectionService.deleteFormItemById({
        ids: [id]
      })
      await this.getFieldList()
    },
    handleExtendDicArrayChange (value) {
      this.fieldInfo.extendDicNames = value.join(',')
    },
    async updateConfigFormItem () {
      if (this.fieldInfo.id) {
        const data = await dataQualityInspectionService.updateConfigFormItem(this.fieldInfo)
        if (data && data.id) {
          this.$message.success('保存成功')
          await this.getFieldList()
        }
      }
    },
    async saveBasicInfo () {
      const { id, name, desc } = this.templateInfo
      const data = await dataQualityInspectionService.updateConfig({ id, name, desc })
      if (data && data.id) {
        this.$message.success('保存成功')
        this.$emit('updatePaneTitle', data)
      }
    },
    async listScriptItemByFormItemId (id) {
      const data = await dataQualityInspectionService.listScriptItemByFormItemId({ formItemId: id })
      this.table.dataSource = data
    },
    async addSciptltem (type) {
      if (type === 'add') {
        const data = {
          formItemId: this.activeField
        }
        const res = await dataQualityInspectionService.saveScriptItem([data])
        await this.listScriptItemByFormItemId(this.activeField)
        if (res.length) {
          this.$message.success('新增成功')
          this.activeScript = res[0].id
        }
      } else if (type === 'save') {
        const res = await dataQualityInspectionService.saveScriptItem(this.table.dataSource)
        if (res.length) {
          this.$message.success('保存成功')
          this.activeScript = ''
        }
      }
    },
    async deleteScript (id) {
      this.$confirm({
        title: '提示',
        content: '确认执行删除操作，删除后自定义脚本不可恢复！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          dataQualityInspectionService.deleteScriptItemById({
            idList: [id]
          }).then(() => {
            this.listScriptItemByFormItemId(this.activeField)
            this.$message.success('删除成功')
          })
        }
      })
    },
    async saveConfigFormInfo () {
      const configFormInfo = JSON.parse(JSON.stringify(this.configFormInfo))
      if (Array.isArray(configFormInfo.activityName)) {
        configFormInfo.activityName = this.configFormInfo.activityName.join(',')
      }
      if (this.configFormInfo.id) {
        await dataQualityInspectionService.updateConfigForm(configFormInfo)
        this.$message.success('保存成功')
      }
    },
    showTestDialog () {
      this.$dialog({
        title: '测试模板',
        content: () => import('./dialog/testTemplateDialog'),
        width: '70vw',
        centered: true,
        maskClosable: false,
        footer: null,
        props: {
          configName: this.template.name
        }
      })
    },
    async initFieldList () {
      await dataQualityInspectionService.initDataQualityFormByCfgFormId({ id: this.activeForm })
      await this.getFieldList()
      this.$message.success('初始化成功')
    },
    showIconSelDialog () {
      const _this = this
      this.$dialog({
        title: '选择图标',
        content: () => import('./dialog/iconSelectDialog'),
        width: 450,
        centered: true,
        maskClosable: false,
        on: {
          ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            _this.configFormInfo.icon = dialogCtl.selectIcon || ''
            ctl.closeDialog()
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.template-detail{
  padding-bottom: 65px;
  .detail-box{
    height: 100%;
    width: 33%;
    overflow-y: auto;
    padding: 10px;
    .item-active{
      background-color: #f5f5f5;
    }
    .item{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      &:hover{
        background-color: #f5f5f5;
      }
      .name{
        width: 90%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        cursor: pointer;
      }
    }
    .detail-title{
      padding-bottom: 10px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .left-info{
    border-right: 1px solid #d6d9dc;
  }
  .center-info{
    border-right: 1px solid #d6d9dc;
  }
  .script-btn{
    cursor: pointer;
    color: #2BAEF2;
  }
  .icon-sel{
    display: flex;
  }
}
</style>
